{extend name="other/public"}
{block name='css'}
 <style>
   .c1 input{width: 100%;}
   .c4{display: none;margin-top: 30px;width: 100%;line-height: 42px;letter-spacing: 1px;text-align: center;color: #fff;background: #009688;font-size: 15px;}
   .c4:hover{cursor: pointer;background: #008578;}
   .c5{display: none;}
 </style>
{/block}

{block name='content'}
<div class="layui-fluid" id="app" v-cloak>
  <div class="layui-row layui-col-space15">
    <div class="layui-col-sm12 layui-col-md5">
      <div class="layui-card">
        <div class="layui-card-header">权限列表</div>
        {eq name="is_super" value="1"}
        <div class="layui-card-header layuiadmin-card-header-auto c1 layui-form">
          <select name="pid" lay-verify="required">
            <option value="0">新增上级</option>
            {volist name="powerLists" id="vo"}
              {eq name="$vo.pid" value="0"}
                <option value="{$vo.id}">{$vo.name}</option>
              {/eq}
            {/volist}
          </select>
          <div style="margin: 10px 0;">
            <input type="text" name="name" class="layui-input"  placeholder="输入权限名称l，如：添加新闻" lay-verify="required" lay-verType="tips" >
          </div>
          <div>
            <input type="text" class="layui-input" name="url" placeholder="输入url，如：news/add_news" lay-verify="required" lay-verType="tips" >
          </div>
          <button class="layui-btn layuiadmin-btn-tags" type="button" lay-submit lay-filter="formDemo">添加权限</button>
        </div>
        {/eq}
        <div class="layui-card-body" style="padding-bottom: 30px;">    
          <div id="power-list"></div>
        </div>
      </div>
    </div>
    <div class="layui-col-sm12 layui-col-md7">
      <div class="layui-card">
        <div class="layui-card-header">角色列表</div>
        <div class="layui-card-header layuiadmin-card-header-auto u-flex c1">
          <input type="text" class="layui-input" v-model="typeName" placeholder="输入需要添加的角色名称">
          <button class="layui-btn layuiadmin-btn-tags" @click="addType">添加角色</button>
        </div>
        <div class="layui-card-body">    
          <table class="layui-table">
            <colgroup>
              <col>
              <col width="200">
            </colgroup>
            <thead>
              <tr>
                <th>角色类型</th>
                <th style="text-align: center;">操作</th>
              </tr> 
            </thead>
            <tbody>
              <tr v-for="(v,index) in listData" :key="index">
                <td>{{v.role_name}}</td>
                <td style="text-align: center;">
                  <a class="layui-btn layui-btn-normal layui-btn-sm layui-btn-disabled" v-if="v.id==1" :data-power="v.power_id" :data-id="v.id">设置权限</a>
                  <a class="layui-btn layui-btn-normal layui-btn-sm c3" v-else :data-power="v.power_id" :data-id="v.id">设置权限</a>
                  <a class="layui-btn layui-btn-danger layui-btn-sm layui-btn-disabled" v-if="v.id==1">删除</a>
                  <a class="layui-btn layui-btn-danger layui-btn-sm"  v-else  @click="delData(v,index)">删除</a>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="c5">
  <div id="power"></div>
</div>
<div class="c4">确定修改</div>

{/block}

{block name='js'}
<script>
  const listData = {$listData|raw};
  const powerList = {$powerList|raw};

  const anVue = new Vue({
    el:"#app",
    data:{
      listData:listData,
      typeName:'',
      powerData:{
        name:'',
        url:''
      }
    },
    methods: {
      addType(){
        if(this.typeName==''){
          layer.msg('请输入需要添加的分类名称')
          return false;
        }
        $.post("{:url('add_role')}",{role_name:this.typeName},(res)=>{
            if(res.code==1){
              layer.msg('操作成功',{time:1000},function(){
                location.reload()
              })
            }else{
              layer.msg(res.msg)
            }
        },'json')
      },
      delData(v,index){
        let _this = this;
        layer.msg('删除后将不能恢复', {
          time: 0 //不自动关闭
          ,btn: ['直接删除', '取消']
          ,yes: function(index){
            layer.close(index);
            $.post("{:url('del_role')}",{id:v.id,role_name:v.role_name},(res)=>{
                if(res.code==1){
                  layer.msg('操作成功',{time:1000},function(){
                    location.reload()
                  })
                }else{
                  layer.msg(res.msg)
                }
            },'json')
          }
        });
      },

    },
  })


  //javascript  树形结构
function toTree(data) {
    // 删除 所有 children,以防止多次调用
    data.forEach(function(item) {
        delete item.children;
    });

    // 将数据存储为 以 id 为 KEY 的 map 索引数据列
    var map = {};
    data.forEach(function(item) {
        // 在该方法中可以给每个元素增加其他属性
        item.title = item.name+' ，'+item.url;
        item.spread = true;
        map[item.id] = item;
    });
    //  console.log(map);

    var val = [];
    data.forEach(function(item) {

        // 以当前遍历项，的pid,去map对象中找到索引的id
        var parent = map[item.pid];

        // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
        if (parent) {
            // 可以给每个父节点添加属性
            parent.iconCls = "i-folder";
            //  添加到父节点的子节点属性中
            (parent.children || (parent.children = [])).push(item);

        } else {
            //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
            val.push(item);
        }
    });
    return val;
}


  layui.config({
    base: '../../../static/layuiadmin/' //静态资源所在路径
  }).extend({
    index: 'lib/index' //主入口模块
  }).use(['index','tree','form'], function(){
    var $ = layui.$,admin = layui.admin
    var tree = layui.tree;
    var form = layui.form;
    form.on('submit(formDemo)', function(data){
      $.post("{:url('power_data')}?add=1",data.field,function(res){
        if(res.code == 1){
          layer.msg('操作成功',{time: 1000},function(){
            location.reload();
          })
        }else{
          layer.msg(res.msg)
        }
      })
      return false;
    });

    var inst1 = tree.render({
      elem: '#power-list'  //绑定元素
      {eq name="is_super" value="1"},edit: ['del']{/eq}
      ,data:toTree(powerList)
      ,operate: function(obj){
          var type = obj.type; //得到操作类型：add、edit、del
          var data = obj.data; //得到当前节点的数据
          var elem = obj.elem; //得到当前节点元素
          var id = data.id;
          if(type === 'del'){

            layer.msg('删除后将不能恢复', {
            time: 0 //不自动关闭
            ,btn: ['直接删除', '取消']
            ,yes: function(index){
              layer.close(index);
              $.post("{:url('power_data')}?del=1",{id,name:data.title},function(res){
                if(res.code == 1){
                  layer.msg('操作成功',{time: 1000},function(){
                    location.reload();
                  })
                }else{
                  layer.msg(res.msg)
                }
              })
            }
          });
        };
      }
    });

    var roleID = '';

    $(".c3").click(function(){
      roleID = $(this).data('id');
      var role_ids = $(this).data('power');

      var roleIdArr;
      if(role_ids != undefined){
        if(typeof(role_ids)!= 'number'){
          roleIdArr = role_ids.split( ',' ).map(Number);
        }else{
          roleIdArr = [role_ids]
        }
      }
      


      tree.render({
        elem: '#power'
        ,id: 'demoId'
        ,showCheckbox:true
        ,showLine:false
        ,data:toTree(powerList)
      });

      if(role_ids != undefined){
        tree.setChecked('demoId', roleIdArr);
      }

      

      var adminPopup = admin.popup({
        title: '权限管理'
        ,anim: -1
        ,area: ['500px', '88%']
        ,id: 'layadmin-layer-skin-test'
        ,scrollbar: false
        ,skin: 'layui-anim layui-anim-upbit'
        ,content: $(".c5"),
        success: function(layero, index){
          $(".c4").show();
          $(".c5").append($(".c4"))
        },
        end: function(index, layero){ 
          $(".c4").hide();
        }   
      })
    })

    $(".c4").click(function(){
      var numberStr = '';
      var checkData = tree.getChecked('demoId');
      checkData.forEach(v=>{
        if(Array.isArray(v.children)){
          v.children.forEach(val=>{
            numberStr += val.id + ','
          })
        }else{
          numberStr += v.id + ','
        }
      })
      numberStr = numberStr.substring(0, numberStr.lastIndexOf(','));
      $.post("{:url('role_power_edit')}",{power_id:numberStr,id:roleID},function(res){
        layer.msg('设置成功')
        $("[data-id="+roleID+"]").data('power',numberStr);
        layer.closeAll('page'); 
      })
    })


  });
  </script>
{/block}